/**
 * Copyright 2012 Viettel Telecome. All rights reserved.
 * VIETTEL PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.viettel.view.MainHome;

import java.io.IOException;
import java.io.Serializable;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import junit.framework.Test;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.w3c.dom.Text;
import org.xbill.DNS.tests.primary;

import com.korovyansk.android.slideout.SlideoutActivity;
import com.markupartist.android.widget.ActionBar;
import com.markupartist.android.widget.ActionBar.AbstractAction;
import com.viettel.R;
import com.viettel.dto.PlaceDTO;
import com.viettel.dto.MainHomeDTO;
import com.viettel.place.GPSTracker;
import com.viettel.place.Place;
import com.viettel.place.PlacesList;
import com.viettel.utils.AlertDialogManager;
import com.viettel.viettellib.json.me.JSONException;
import com.viettel.viettellib.json.me.JSONObject;
import com.viettel.viettellib.network.http.ConnectionDetector;
import com.viettel.viettellib.network.http.GooglePlaces;
import com.viettel.view.common.ViewUtils;
import com.whathots.menu.MenuActivity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.database.DataSetObserver;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.location.Address;
import android.location.Geocoder;
import android.opengl.Visibility;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.text.Html;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

/**
 *  Mo ta muc dich cua lop (interface)
 *  @author: HOC
 *  @version: 1.0
 *  @since: Sep 14, 2012
 */
@SuppressLint("ResourceAsColor")
public class SelectEventPlace extends Activity  {
	View menu;
    View app;
	EditText txt_place;
	ImageButton btnSearchPlace;
	ListView listViewPlace;
	Handler handle = new Handler();
	AlertDialogManager alertDialog = new AlertDialogManager();
	Button btnSelectPlaceDefault;
	// Progress dialog
	ProgressDialog pDialog;
	ArrayList<PlaceDTO> placeDataList = new ArrayList<PlaceDTO>();
	
	// Google Places
	GooglePlaces googlePlaces;

	// Places List
	PlacesList nearPlaces;

	// GPS Location
	GPSTracker gps;	
	
	// Connection detector class
	ConnectionDetector cd;
		
	// flag for Internet connection status
	Boolean isInternetPresent = false;
		
	LinearLayout viewParent;	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		LayoutInflater lf = LayoutInflater.from(this);
		
		app = lf.inflate(R.layout.layout_select_event_place, null);
		setContentView(app);
		
		//init actionBar
		ActionBar actionBar = (ActionBar) app.findViewById(R.id.actionbar);
		actionBar.setTitle(getResources().getString(R.string.SELECT_PLACE));
		
		viewParent = (LinearLayout) app.findViewById(R.id.viewParent);
		
		txt_place 		= (EditText) app.findViewById(R.id.txt_place);
		btnSearchPlace 	= (ImageButton) app.findViewById(R.id.btnSearchPlace);
		btnSelectPlaceDefault = createSelectPlaceDefaultButton();
		
		
		//listview
		listViewPlace = (ListView) app.findViewById(R.id.listViewPlace);
		listViewPlace.setDividerHeight(0);
		
		
		cd = new ConnectionDetector(getApplicationContext());

		// Check if Internet present
		isInternetPresent = cd.isConnectingToInternet();
		if (!isInternetPresent) {
			// Internet Connection is not present
			alertDialog.showAlertDialog(SelectEventPlace.this, "Internet Connection Error",
					"Please connect to working Internet connection", false);
			// stop executing code by return
			return;
		}
		
		// creating GPS Class object
		gps = new GPSTracker(SelectEventPlace.this);
		
		// check if GPS location can get
		if (!gps.canGetLocation()) {
			// Can't get user's current location
			alertDialog.showAlertDialog(SelectEventPlace.this, "GPS Status",
					"Couldn't get location information. Please enable GPS",false);
			return;
		} 
		
		//kiem tra GPS
		btnSearchPlace.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				String placeText = txt_place.getText().toString();
				
				if (placeText.equals("") || placeText.equals(null)){
					alertDialog.showAlertDialog(SelectEventPlace.this, "Places Error","Place enter place",false);
					showSelectPlaceDefaultButton();
				}else{
					//hiddenSelectPlaceDefaultButton();
					
					placeDataList.add(new PlaceDTO(null, "hahaha", "532D, XVNT,p.25,quan Binh Thanh"));
					placeDataList.add(new PlaceDTO(null, "hehehe", "532D, XVNT,p.25,quan Binh Thanh"));
					placeDataList.add(new PlaceDTO(null, "hahaha", "532D, XVNT,p.25,quan Binh Thanh"));
					placeDataList.add(new PlaceDTO(null, "hahaha", "532D, XVNT,p.25,quan Binh Thanh"));
					placeDataList.add(new PlaceDTO(null, "hahaha", "532D, XVNT,p.25,quan Binh Thanh"));
					placeDataList.add(new PlaceDTO(null, "hahaha", "532D, XVNT,p.25,quan Binh Thanh"));
					placeDataList.add(new PlaceDTO(null, "hahaha", "532D, XVNT,p.25,quan Binh Thanh"));
					placeDataList.add(new PlaceDTO(null, "hahaha", "532D, XVNT,p.25,quan Binh Thanh"));
					
					listViewPlace.setAdapter(new Whatshosts_Search_Place_Adapter(SelectEventPlace.this, placeDataList));
					listViewPlace.setOnItemClickListener(new OnItemClickListener() {
			
						@Override
						public void onItemClick(AdapterView<?> parent, View v, int postion,long id) {
							String placeDetail = placeDataList.get(postion).getTxt_Name() + "," + placeDataList.get(postion).getTxt_Address();
							Intent intent = new Intent(SelectEventPlace.this, CreateNewEvent.class);
							intent.putExtra("EVENT_PLACE", placeDetail);
							startActivity(intent);
						}
					});
					
					//new LoadPlaces().execute();
				}
			}
		});
		
		final View[] children = new View[] { app };
	}

	
	
	
	public Button createSelectPlaceDefaultButton(){
    	LayoutParams lp = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
		Button button = new Button(getApplicationContext());
		button.setLayoutParams(lp);
		button.setPadding(0, 5, 0, 10);
		button.setText(Html.fromHtml(getResources().getString(R.string.PLACE_NOT_FOUNT)+"<br/>Sử dụng địa chỉ \"<b>"+getResources().getString(R.string.PLACE_DEFAULT)+"</b>\""));
		button.setTextColor(Color.BLACK);
		button.setTextSize(16);
		
		return button;
    }
	
	
	public void showSelectPlaceDefaultButton(){
    	viewParent.removeView(listViewPlace);
		viewParent.addView(btnSelectPlaceDefault);
	}
    
    public void hiddenSelectPlaceDefaultButton(){
    	viewParent.removeView(btnSelectPlaceDefault);
		viewParent.addView(listViewPlace);
    }
	
	
	
	/**
	 * Background Async Task to Load Google places
	 * */
	class LoadPlaces extends AsyncTask<String, String, String>{
		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(SelectEventPlace.this);
			pDialog.setMessage(Html.fromHtml("<b>Search</b><br/>Loading Places..."));
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}
		
		
		/**
		 * getting Places JSON
		 * */
		@Override
		protected String doInBackground(String... args) {
			// creating Places class object
			googlePlaces = new GooglePlaces();
			
			try {
				// Separeate your place types by PIPE symbol "|"
				// If you want all types places make it as null
				// Check list of types supported by google
				// 
				String types = "cafe|restaurant"; // Listing places only cafes, restaurants
				
				// Radius in meters - increase this value if you don't find any places
				double radius = 1000; // 1000 meters 
				
				// get nearest places
				double lat = gps.getLatitude();
				double lng =  gps.getLongitude();
				nearPlaces =  googlePlaces.search(lat,lng, radius, types);
				
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			return null;
		}
		
		/**
		 * After completing background task Dismiss the progress dialog
		 * and show the data in UI
		 * Always use runOnUiThread(new Runnable()) to update UI from background
		 * thread, otherwise you will get error
		 * **/
		protected void onPostExecute(String file_url) {
			// dismiss the dialog after getting all products
			pDialog.dismiss();
			// updating UI from Background Thread
			runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					/**
					 * Updating parsed Places into LISTVIEW
					 * */
					// Get json response status
					String status = nearPlaces.status;
					
					// Check for all possible status
					if(status.equals("OK")){
						// Successfully got places details
						if (nearPlaces.results != null) {
							// loop through each place
							for (Place p : nearPlaces.results) {
								PlaceDTO placeItem = new PlaceDTO();
								placeItem.setBm_place(getBitmapPlaceIcon(p.icon));
								placeItem.setTxt_Name(p.name);
								placeItem.setTxt_Address(p.formatted_address);
								
								placeDataList.add(placeItem);
							}
							
							if (placeDataList.isEmpty()) {
								showSelectPlaceDefaultButton();
							}else{
								hiddenSelectPlaceDefaultButton();
								
								listViewPlace.setAdapter(new Whatshosts_Search_Place_Adapter(SelectEventPlace.this, placeDataList));
								listViewPlace.setOnItemClickListener(new OnItemClickListener() {
						
									@Override
									public void onItemClick(AdapterView<?> parent, View v, int postion,long id) {
										String placeDetail = placeDataList.get(postion).getTxt_Name() + "," + placeDataList.get(postion).getTxt_Address();
										Intent intent = new Intent(SelectEventPlace.this, CreateNewEvent.class);
										intent.putExtra("EVENT_PLACE", placeDetail);
										startActivity(intent);
									}
								});
							}
						}
					}
					else if(status.equals("ZERO_RESULTS")){
						// Zero results found
						alertDialog.showAlertDialog(SelectEventPlace.this, "Near Places",
								"Sorry no places found. Try to change the types of places",
								false);
					}
					else if(status.equals("UNKNOWN_ERROR"))
					{
						alertDialog.showAlertDialog(SelectEventPlace.this, "Places Error",
								"Sorry unknown error occured.",
								false);
					}
					else if(status.equals("OVER_QUERY_LIMIT"))
					{
						alertDialog.showAlertDialog(SelectEventPlace.this, "Places Error",
								"Sorry query limit to google places is reached",
								false);
					}
					else if(status.equals("REQUEST_DENIED"))
					{
						/*alertDialog.showAlertDialog(SelectEventPlace.this, "Places Error",
								"Sorry error occured. Request is denied",
								false);*/
						showSelectPlaceDefaultButton();
						btnSelectPlaceDefault.setOnClickListener(new OnClickListener() {
							
							@Override
							public void onClick(View v) {
								// TODO Auto-generated method stub
								String placeDetail = "Nhà văn hóa Phụ Nữ";
								Intent intent = new Intent(SelectEventPlace.this, CreateNewEvent.class);
								intent.putExtra("EVENT_PLACE", placeDetail);
								startActivity(intent);
							}
						});
						//viewParent.addView(btnSelectPlaceDefault);
					}
					else if(status.equals("INVALID_REQUEST"))
					{
						alertDialog.showAlertDialog(SelectEventPlace.this, "Places Error",
								"Sorry error occured. Invalid Request",
								false);
					}
					else
					{
						alertDialog.showAlertDialog(SelectEventPlace.this, "Places Error",
								"Sorry error occured.",
								false);
					}
				}
			});
		}
	}
	
	
	public Bitmap getBitmapPlaceIcon(String urlIcon){
		Bitmap bm = BitmapFactory.decodeFile(urlIcon);
		return bm;
	}
	
	

	//Create Adapter for listview location
	public class Whatshosts_Search_Place_Adapter extends BaseAdapter{

		private Context mContext;
		private LayoutInflater lf;
		private ArrayList<PlaceDTO> arrListPlaces;
		class ViewHolder{
			ImageView icon_Place;
			TextView txt_Name;
			TextView txt_Address;
		}
		
		
		/**
		 * Constructor
		 */
		public Whatshosts_Search_Place_Adapter(Context context) {
			//mContext		=	context;
			lf = LayoutInflater.from(context);
		}
		
		
		/**
		 * Constructor
		 */
		public Whatshosts_Search_Place_Adapter(Context context, ArrayList<PlaceDTO> listPlaces) {
			//mContext		=	context;
			lf = LayoutInflater.from(context);
			arrListPlaces	=	listPlaces;
		}
		
		
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			if (arrListPlaces != null) {
				return arrListPlaces.size();
			}
			else{
				return 0;
			}
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return arrListPlaces.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		
		/**
		*  Mo ta chuc nang cua ham
		*  @author: BangHN
		*  @param viewHolder
		*  @param position
		*  @return: void
		*  @throws: 
		*/
		private void publicView(ViewHolder view, int position) {
			PlaceDTO dto = arrListPlaces.get(position);
			//view.icon_Place.setImageBitmap(dto.getBm_place());
        	view.txt_Name.setText(dto.getTxt_Name());
        	view.txt_Address.setText(dto.getTxt_Address());
		}
		
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder viewHolder;
			
			if (convertView == null) {
                convertView = lf.inflate(R.layout.layout_select_event_place_item, null);
                viewHolder = new ViewHolder();
                viewHolder.icon_Place 		= (ImageView) convertView.findViewById(R.id.icon_place);
                viewHolder.txt_Name 			= (TextView) convertView.findViewById(R.id.txtName);
                viewHolder.txt_Address 			= (TextView) convertView.findViewById(R.id.txtAddress);
                convertView.setTag(viewHolder);
            } else {
            	viewHolder = (ViewHolder) convertView.getTag();
            }
            publicView(viewHolder,position);
            return convertView;
		}


		
		
	}//End Whatshosts_Search_Location_Adapter

	private  class MyIntentAction extends AbstractAction {
        private Context mContext;
        private Intent mIntent;

        public MyIntentAction(Context context, Intent intent, int drawable) {
            super(drawable);
            mContext = context;
            mIntent = intent;
        }

        @Override
        public void performAction(View view) {
            try {
            	handle.post(new Runnable(){
            		public void run(){
            		//Update UI
         			int width = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 40, getResources().getDisplayMetrics());
        			SlideoutActivity.prepare(SelectEventPlace.this, R.id.inner_content, width);
        			startActivity(new Intent(SelectEventPlace.this,
        								MenuActivity.class));
        			overridePendingTransition(0, 0);
            		}
            		});
            } catch (ActivityNotFoundException e) {
                Log.e(this.getClass().toString(), e.getMessage());
            }
        }
    }


   
    /**
     * Helper for examples with a HSV that should be scrolled by a menu View's width.
     */
    static class ClickListenerForScrolling implements OnClickListener {
        HorizontalScrollView scrollView;
        View menu;
        /**
         * Menu must NOT be out/shown to start with.
         */
        boolean menuOut = false;

        public ClickListenerForScrolling(HorizontalScrollView scrollView, View menu) {
            super();
            this.scrollView = scrollView;
            this.menu = menu;
        }

        @Override
        
        public void onClick(View v) {
            Context context = menu.getContext();
            String msg = "Slide " + new Date();
            //Toast.makeText(context, msg, 1000).show();
            System.out.println(msg);
            Log.i("ScreenSingleton", msg);
            int menuWidth = menu.getMeasuredWidth();

            // Ensure menu is visible
            menu.setVisibility(View.VISIBLE);

            if (!menuOut) {
                // Scroll to 0 to reveal menu
                int left = 0;
                scrollView.smoothScrollTo(left, 0);
            } else {
                // Scroll to menuWidth so menu isn't on screen.
                int left = menuWidth;
                scrollView.smoothScrollTo(left, 0);
            }
            menuOut = !menuOut;
        }
    }

    /**
     * Helper that remembers the width of the 'slide' button, so that the 'slide' button remains in view, even when the menu is
     * showing.
     */
}
